<template>
	<div class="content">
		<div class="pageSearchView" style="display: flex; justify-content: space-between; align-items: center;">
			<el-form :inline="true" :model="searchParam" class="demo-form-inline">
				<el-form-item label="计划号">
					<el-input v-model="searchParam.planNo" placeholder="请输入计划号" clearable style="width: 200px" />
				</el-form-item>
				<el-form-item>
					<el-button :icon="Search" @click="getList()">查询</el-button>
				</el-form-item>
			</el-form>
			<el-button style="margin-top: -1%;" :icon="Reading" :disabled="!searchParam.planNo"
				@click="showDialog()">详情</el-button>
		</div>
		<div class="pageTableView" v-if="paginatedData.length > 0">
			<div class="leftView">
				<div class="nodeList" v-for="(item, index) of paginatedData" :key="index"
					:class="index == tabIndex ? 'boxShow' : ''" @click="leftChange(index)">
					<div class="nodeBody" :class="item.count > 0 ? 'yellowView' : 'redView'">
						<div class="nodeTitle"> {{ item.procedureName }}</div>
						<div class="nodeInfo">
							<div> 计划数：<span>{{ item.planNumber || 0 }}</span></div>
							<div> 报工数：<span>{{ item.count || 0 }}</span></div>
							<div> 未完成：<span>{{ item.unFinishNumber || 0 }}</span></div>
						</div>
					</div>
				</div>
			</div>
			<div class="rightView">
				<el-tabs v-model="isWorkStatusTab" class="demo-tabs" @tab-click="handleClick">
					<el-tab-pane label="投料详情" name="false">
						<el-table :data="throwMaterialRecords" height="calc(100vh - 270px)" row-key="id" :stripe="false"
							class="sort-el-table" header-cell-class-name="witheTableHeader">
							<el-table-column type="index" label="序号" width="80" align="center" />
							<el-table-column prop="batchNo" label="批次号" align="center" min-width="150" />
							<el-table-column prop="materialName" label="物料名称" align="center" min-width="200"
								show-overflow-tooltip />
							<el-table-column prop="materialCount" label="投料数量" align="center" />
							<el-table-column prop="createTime" label="投料时间" align="center" />
							<!--							<el-table-column prop="createUser" label="创建人" width="150" align="center" />-->
						</el-table>
					</el-tab-pane>
					<el-tab-pane label="报工详情" name="true">
						<el-table :data="reportWorkRecordVOS" height="calc(100vh - 270px)" row-key="id" :stripe="false"
							class="sort-el-table" header-cell-class-name="witheTableHeader">
							<el-table-column type="index" label="序号" width="80" align="center" />
							<el-table-column prop="reportWorkRecordNo" label="批次号" align="center" min-width="160" />
							<el-table-column prop="materialOutName" label="产出物料" align="center" min-width="220" />
							<el-table-column prop="reportTraceCode" label="追溯码" align="center" min-width="210" />
							<el-table-column prop="count" label="报工数量" align="center" width="150" />
							<el-table-column prop="status" label="物料状态" :formatter="statusType" align="center" />
							<el-table-column prop="createTime" label="报工时间" align="center" min-width="180" sortable />
							<!--							<el-table-column prop="createUser" label="创建人" width="150" align="center" />-->
						</el-table>
					</el-tab-pane>
				</el-tabs>
			</div>
		</div>
		<div class="pageTableView" style="display: flex;justify-content: center;align-items: center;color: #777;"
			v-else> 暂无数据 </div>
		<el-dialog v-model="dialogRef" title="计划详情" @close="onCloseButton" width="98%">
			<div class="dialog-content">
				<div ref="echartsContainer" style="width: 100%; height: 600px;"></div>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCloseButton">关闭</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="ts" setup>
import { ref, computed, watch, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { queryByPlanIdDetail } from '@/api/production/productionPlan';
import {
	Delete, Edit, Tickets, DocumentChecked
	, Search, Share, Upload, Refresh, Plus, DocumentCopy, Files, Reading
} from '@element-plus/icons-vue';
import axiosInstance from '@/utils/http/api';
import draggable from 'vuedraggable';
import { useRoute, useRouter } from 'vue-router';
import * as echarts from 'echarts';

const route = useRoute();
const searchParam = ref({});
const paginatedData = ref([]);
const activeNodeIndex = ref(0);
const isWorkStatusTab = ref('false');
const isWorkStatus = ref('false');
const dialogRef = ref(false);
const echartsContainer = ref(null);
const chartDom = ref({});
const showDialog = () => {
	dialogRef.value = true;
	nextTick(() => {
		const chart = echarts.init(echartsContainer.value);
		queryByPlanIdDetail({ planNo: searchParam.value.planNo }).then(res => {
			if (res.code == 200) {
				chartDom.value = res.data;
				var layerOneNumber = 0;
				res.data.children.forEach(item => {
					layerOneNumber += item.planCount;
				});
				const mockData = generateMockData([res.data], layerOneNumber);
				const { nodes, links } = mockData;

				const option = {
					tooltip: {
						trigger: 'item',
						triggerOn: 'mousemove',
						formatter: params => {
							// 自定义提示框显示的内容
							return params.name; // 仅显示 name
						}
					},
					series: {
						type: 'sankey',
						layout: 'none',
						nodeAlign: 'left',
						emphasis: {
							focus: 'adjacency'
						},
						data: nodes,
						links: links,
						lineStyle: {
							color: 'source',
							curveness: 0.5
						}
					}
				};

				chart.setOption(option);
			} else {
				chart.setOption(null);
			}
		})


	});
}
const generateMockData = (data, num) => {
	const nodes = [];
	const links = [];

	data?.map((item) => {
		const orderPlan = '计划号' + item.planNo;
		nodes.push({ name: orderPlan });
		item.children.forEach((i) => {
			const orderPlan1 = '数量' + i.planCount + '产品' + i.productName;
			nodes.push({ name: orderPlan1 });
			links.push({ source: orderPlan, target: orderPlan1, value: i.planCount });
			if (!i.children) {
				return;
			}
			i.children.map((s, index) => {
				const orderPlan2 = '数量' + s.orderCount + '工序订单' + s.no;
				const childValue = Math.round(i.planCount * (s.orderCount / (i.children.reduce((acc, curr) => acc + curr.orderCount, 0))));
				nodes.push({ name: orderPlan2 });
				links.push({ source: orderPlan1, target: orderPlan2, value: childValue });
				if (s.children && s.factionWork) {
					if (s.factionWork.count !== 0) {
						const factionWorkValue = Math.round(childValue * (s.factionWork.count / s.orderCount));
						const orderPlan3 = '工序订单' + s.no;
						nodes.push({ name: orderPlan3 + '未派工数量:' + s.factionWork.count });
						links.push({
							source: orderPlan2,
							target: orderPlan3 + '未派工数量:' + s.factionWork.count,
							orderPlan2,
							value: factionWorkValue
						});
					}

				} else {
					const orderPlan3 = '工序订单' + s.no;
					nodes.push({ name: orderPlan3 + '未派工数量:' + s.orderCount });
					links.push({
						source: orderPlan2,
						target: orderPlan3 + '未派工数量:' + s.orderCount,
						orderPlan2,
						value: childValue
					});
				}
				if (!s.children) {
					return;
				}
				s.children.map((n) => {
					const factionWorkValues = Math.round(childValue * (n.orderCount / s.orderCount));
					const orderPlan3 = '数量' + n.orderCount + '工单' + n.workNo;

					nodes.push({ name: orderPlan3 });
					links.push({ source: orderPlan2, target: orderPlan3, value: factionWorkValues });
				});
			});
		});
	});
	return { nodes, links };
};
const onCloseButton = () => {
	dialogRef.value = false;
};
const handleClick = (tab: TabsPaneContext, event: Event) => {
	isWorkStatus.value = tab.paneName;
	if (searchParam.value.id) {
		getList();
	}
};

const statusType = (e) => {
	const list = [{
		label: '不合格',
		value: '0'
	}, {
		label: '合格',
		value: '1'
	}, {
		label: '报废',
		value: '2'
	}];
	const type = list.find(type => type.value == e.status);
	return type ? type.label : '';
};


// 获取列表
const getList = async () => {
	if (!searchParam.value.planNo) {
		ElMessage.error('请输入计划号')
		return false
	}
	paginatedData.value = [];
	axiosInstance.get('/api/throwMaterialRecord/queryAllPlanDetailById', {
		params: {
			...searchParam.value
		}
	})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			if (res.data.length == 0) {
				ElMessage.error('未查询到数据');
				return false;
			}

			let list = res.data;
			list.sort((a, b) => a.index - b.index);
			paginatedData.value = list;
			leftChange(0);
		});
};

const throwMaterialRecords = ref([]);
const reportWorkRecordVOS = ref([]);
const tabIndex = ref(0);
const leftChange = (index) => {
	tabIndex.value = index;
	if (paginatedData.value[index].throwMaterialRecords) {
		throwMaterialRecords.value = paginatedData.value[index].throwMaterialRecords;
	} else {
		throwMaterialRecords.value = [];
	}


	if (paginatedData.value[index].reportWorkRecordVOS) {
		reportWorkRecordVOS.value = paginatedData.value[index].reportWorkRecordVOS;
	} else {
		reportWorkRecordVOS.value = [];
	}
};

onMounted(() => {
	searchParam.value.planNo = route.query.planNo
	if (searchParam.value.planNo) {
		getList()
	}
});
</script>
<style scoped>
.leftView {
	height: 100%;
	width: 450px;
	overflow-y: auto;
}

.rightView {
	width: calc(100% - 451px);
	height: 100%;
	padding: 0 10px;
}

.pageTableView {
	height: calc(100vh - 190px);
	display: flex;
}


.nodeList {
	width: 420px;
	display: flex;
	flex-direction: column;
	box-sizing: border-box;
	margin: 10px 0 25px 0;
	user-select: none;
	border-radius: 15px;
	font-weight: bolder;
	cursor: pointer;
}

.nodeBody {
	border-radius: 5px;
	padding: 8px 10px;
}

.nodeTitle {
	width: 100%;
	padding: 15px 10px 5px 10px;
	font-weight: 700;
	border-radius: 10px 10px 0 0;
	font-weight: 700;
	font-size: 20px;
}

.yellowView {
	background-color: #C1D1FF;
	color: #555;
}

.redView {
	background-color: #D1D1D1;
	color: #666;
}

.boxShow {
	box-shadow: 0 10px 14px 0 rgba(0, 20, 45, 0.2);
}

.nodeInfo {
	display: flex;
	padding: 10px;
	justify-content: space-between;
	color: #777;
	font-size: 15px;
}

.nodeInfo>div {
	width: 33%;
}


.nodeInfo>div>span {
	font-weight: 700;
}
</style>
